<template>
  <el-drawer
    class="project-drawer"
    v-model="open"
    destroy-on-close
    append-to-body
    @close="closeDrawer"
  >
    <div class="close-icon" @click="closeDrawer">
      <el-icon><Close /></el-icon>
    </div>

    <div class="layout-process">
      <div class="layout-process-left">
        <div class="left-head">
          <div class="left-head_title">{{ title }}</div>
          <div class="left-head_info">
            <div class="info-value">
              <dc-view v-model="userInfo.user_id" objectName="user" showKey="realName" />
            </div>
            |
            <div class="info-value">
              发起于{{ info?.createTime || proxy.$dayjs().format('YYYY-MM-DD HH:mm:ss') }}
            </div>
          </div>
        </div>
        <div class="left-body">
          <div class="wrap">
            <el-form
              class="custom-form"
              ref="ruleFormRef"
              :model="formData"
              :rules="rules"
              label-width="150px"
              status-icon
              :inline="true"
            >
              <div class="wrap-left-form">
                <div class="form-group-title">基本信息</div>
                <el-form-item
                  class="form-itme-width_100"
                  label="客户产品"
                  id="customerProductName"
                  prop="customerProductName"
                >
                  <el-select
                    v-model="formData.customerProductName"
                    clearable
                    placeholder="请选择客户产品"
                    @change="handleSelect"
                  >
                    <el-option
                      v-for="item in selectList"
                      :key="item.fnumber"
                      :label="item.fdatavalue"
                      :value="item.fnumber"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="Project"
                  id="projectConfigId"
                  prop="projectConfigId"
                >
                  <dc-select-dialog
                    v-model="formData.projectConfigId"
                    placeholder="请选择关联项目"
                    objectName="projectConfig"
                    type="input"
                    :multiple="false"
                    :multiple-limit="1"
                    :clearable="true"
                    :params="{
                      enabled: true,
                    }"
                    @change="hanleProjectConfig"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="Station"
                  id="stationConfigId"
                  prop="stationConfigId"
                >
                  <dc-select-dialog
                    v-model="formData.stationConfigId"
                    placeholder="请选择关联驻地"
                    objectName="stationConfig"
                    type="input"
                    :multiple="false"
                    :multiple-limit="1"
                    :clearable="true"
                    :params="{
                      stationEnable: true,
                    }"
                    @change="hanleStationConfig"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="计划单号"
                  id="lineName"
                  prop="lineName"
                >
                  <el-input v-model="formData.lineName" placeholder="请输入计划单名称" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="计划单编号"
                  id="lineCode"
                  prop="lineCode"
                >
                  <el-input v-model="formData.lineCode" placeholder="由系统自动生成" disabled />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="CM厂商"
                  id="customerId"
                  prop="customerId"
                >
                  <dc-select-dialog
                    v-model="formData.customerId"
                    placeholder="请选择CM厂商"
                    objectName="customer"
                    type="input"
                    :multiple="false"
                    :multiple-limit="1"
                    :clearable="true"
                    :params="{
                      isCm: true,
                    }"
                    @change="changeCustomer"
                  />
                </el-form-item>
                <el-form-item class="form-itme-width_50" label="区域" id="region" prop="region">
                  <el-cascader
                    v-model="formData.region"
                    :options="areaOptions"
                    :props="{
                      label: 'title',
                      value: 'title',
                    }"
                    @change="handleChange"
                    clearable
                    style="width: 100%"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="负责人"
                  id="chargeUser"
                  prop="chargeUser"
                >
                  <dc-select-user
                    v-model="formData.chargeUser"
                    placeholder="请选择负责人"
                    returnType="string"
                    :multiple="false"
                    :multiple-limit="1"
                    @click.stop
                  />
                </el-form-item>
                <el-form-item class="form-itme-width_50" label="TPMDRI" id="tpmId" prop="tpmId">
                  <dc-select-user
                    v-model="formData.tpmId"
                    placeholder="请选择TPMDRI"
                    returnType="object"
                    :multiple="false"
                    :multiple-limit="1"
                    @click.stop
                    @change="handleTpmChange"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="所属部门"
                  id="deptName"
                  prop="deptName"
                >
                  <el-select
                    v-model="formData.deptName"
                    clearable
                    placeholder="请选择所属部门"
                    @change="handleSelect"
                  >
                    <el-option
                      v-for="item in deptList"
                      :key="item.productCode"
                      :label="item.produdictKeyctCode"
                      :value="item.productCode"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="项目类型"
                  id="mmrPlanOrderType"
                  prop="mmrPlanOrderType"
                >
                  <el-select
                    v-model="formData.mmrPlanOrderType"
                    clearable
                    placeholder="请选择项目类型"
                    @change="handleSelect"
                  >
                    <el-option
                      v-for="item in DC_MMR_PLAN_TYPE"
                      :key="item.dictKey"
                      :label="item.dictValue"
                      :value="item.dictKey"
                    />
                  </el-select>
                </el-form-item>
                <div class="form-group-title">架线</div>
                <el-form-item
                  class="form-itme-width_50"
                  label="单线架线人数"
                  id="singleLbuCount"
                  prop="singleLbuCount"
                >
                  <el-input-number class="w-full" v-model="formData.singleLbuCount" :min="0" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="单独下PO人数"
                  id="singleLbuPoCount"
                  prop="singleLbuPoCount"
                >
                  <el-input-number class="w-full" v-model="formData.singleLbuPoCount" :min="0" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="包含机台报价内人数"
                  id="singleLbuPriceNumber"
                  prop="singleLbuPriceNumber"
                >
                  <el-input-number
                    class="w-full"
                    v-model="formData.singleLbuPriceNumber"
                    :min="0"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="FREE人数"
                  id="singleLbuFreeCount"
                  prop="singleLbuFreeCount"
                >
                  <el-input-number class="w-full" v-model="formData.singleLbuFreeCount" :min="0" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="报价开始时间"
                  id="singleLbuStartDate"
                  prop="singleLbuStartDate"
                >
                  <el-date-picker
                    v-model="formData.singleLbuStartDate"
                    type="date"
                    placeholder="请选择报价开始时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="报价结束时间"
                  id="singleLbuEndDate"
                  prop="singleLbuEndDate"
                >
                  <el-date-picker
                    v-model="formData.singleLbuEndDate"
                    type="date"
                    placeholder="请选择报价结束时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>

                <div class="form-group-title">守线</div>
                <el-form-item
                  class="form-itme-width_50"
                  label="单线守线人数"
                  id="singleSusCount"
                  prop="singleSusCount"
                >
                  <el-input-number class="w-full" v-model="formData.singleSusCount" :min="0" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="单独下PO人数"
                  id="singleSusPoCount"
                  prop="singleSusPoCount"
                >
                  <el-input-number class="w-full" v-model="formData.singleSusPoCount" :min="0" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="包含机台报价内人数"
                  id="singleSusPriceNumber"
                  prop="singleSusPriceNumber"
                >
                  <el-input-number
                    class="w-full"
                    v-model="formData.singleSusPriceNumber"
                    :min="0"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="FREE人数"
                  id="singleSusFreeCount"
                  prop="singleSusFreeCount"
                >
                  <el-input-number class="w-full" v-model="formData.singleSusFreeCount" :min="0" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="报价开始时间"
                  id="singleSusStartDate"
                  prop="singleSusStartDate"
                >
                  <el-date-picker
                    v-model="formData.singleSusStartDate"
                    type="date"
                    placeholder="请选择报价开始时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="报价结束时间"
                  id="singleSusEndDate"
                  prop="singleSusEndDate"
                >
                  <el-date-picker
                    v-model="formData.singleSusEndDate"
                    type="date"
                    placeholder="请选择报价结束时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <div class="form-group-title">爬坡</div>
                <el-form-item
                  class="form-itme-width_50"
                  label="单线爬坡人数"
                  id="singleRampCount"
                  prop="singleRampCount"
                >
                  <el-input-number class="w-full" v-model="formData.singleRampCount" :min="0" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="单独下PO人数"
                  id="singleRampPoCount"
                  prop="singleRampPoCount"
                >
                  <el-input-number class="w-full" v-model="formData.singleRampPoCount" :min="0" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="包含机台报价内人数"
                  id="singleRampPriceNumber"
                  prop="singleRampPriceNumber"
                >
                  <el-input-number
                    class="w-full"
                    v-model="formData.singleRampPriceNumber"
                    :min="0"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="FREE人数"
                  id="singleRampFreeCount"
                  prop="singleRampFreeCount"
                >
                  <el-input-number class="w-full" v-model="formData.singleRampFreeCount" :min="0" />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="报价开始时间"
                  id="singleRampStartDate"
                  prop="singleRampStartDate"
                >
                  <el-date-picker
                    v-model="formData.singleRampStartDate"
                    type="date"
                    placeholder="请选择报价开始时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="报价结束时间"
                  id="singleRampEndDate"
                  prop="singleRampEndDate"
                >
                  <el-date-picker
                    v-model="formData.singleRampEndDate"
                    type="date"
                    placeholder="请选择报价结束时间"
                    format="YYYY/MM/DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>

                <div class="form-group-title">人员占比</div>
                <el-form-item
                  class="form-itme-width_50"
                  label="L1人占比"
                  id="levelOneRate"
                  prop="levelOneRate"
                >
                  <el-input-number
                    class="w-full"
                    v-model="formData.levelOneRate"
                    :min="0"
                    :step="1"
                  >
                    <template #suffix>
                      <span>%</span>
                    </template></el-input-number
                  >
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="L2人占比"
                  id="levelTwoRate"
                  prop="levelTwoRate"
                >
                  <el-input-number
                    class="w-full"
                    v-model="formData.levelTwoRate"
                    :min="0"
                    :step="1"
                  >
                    <template #suffix>
                      <span>%</span>
                    </template></el-input-number
                  >
                </el-form-item>
                <el-form-item
                  class="form-itme-width_50"
                  label="L3人占比"
                  id="levelThreeRate"
                  prop="levelThreeRate"
                >
                  <el-input-number
                    class="w-full"
                    v-model="formData.levelThreeRate"
                    :min="0"
                    :step="1"
                  >
                    <template #suffix>
                      <span>%</span>
                    </template></el-input-number
                  >
                </el-form-item>
                <div class="form-group-title">数量</div>
                <el-form-item label="单线模组数量" prop="moduleCount" class="form-itme-width_50">
                  <el-input-number class="w-full" :min="1" v-model="formData.moduleCount" />
                </el-form-item>
                <el-form-item label="线体数量" prop="lineCount" class="form-itme-width_50">
                  <el-input-number class="w-full" :min="1" v-model="formData.lineCount" />
                </el-form-item>

                <div class="form-group-title">其他信息</div>
                <el-form-item class="form-itme-width_100" label="备注说明" id="notes" prop="notes">
                  <el-input
                    v-model="formData.notes"
                    :rows="4"
                    type="textarea"
                    placeholder="请输入备注说明"
                  />
                </el-form-item>
                <el-form-item
                  class="form-itme-width_100"
                  label="上传附件"
                  id="attachment"
                  prop="attachment"
                >
                  <dc-upload
                    v-model="formData.attachment"
                    :targetType="Const.targetType.MMR_PLAN_ORDER"
                  />
                </el-form-item>
              </div>
            </el-form>
          </div>
        </div>
        <div class="left-footer">
          <el-button type="primary" @click="submitForm" v-loading="loading">提交</el-button>
        </div>
      </div>
    </div>
  </el-drawer>
</template>
<script setup>
import { onMounted, reactive } from 'vue';
import Api from '@/api/index';
import store from '@/store/index';
import Const from '@/const';
import { useRoute } from 'vue-router';
const route = useRoute();
const emit = defineEmits(['confirm']);
const { proxy } = getCurrentInstance();
// 用户信息
const userInfo = computed(() => store.getters.userInfo);

const props = defineProps({
  projectInfo: {
    type: Object,
    default: {},
  },
  isShowChild: {
    type: Boolean,
    default: true,
  },
});

// 数据字典
const { DC_MMR_PLAN_TYPE } = proxy.useCache([{ key: 'DC_MMR_PLAN_TYPE' }]);

const compData = reactive({
  loading: false,
  open: false,
  formData: {
    tpmId: null,
    customerProductCode: null,
    moduleCount: 1,
    lineCount: 1,
    levelOneRate: 30,
    levelTwoRate: 60,
    levelThreeRate: 10,
    customerProductCode: null,
    projectCode: null,
    stationCode: null,
    cmCode: null,
    country: '',
    province: '',
    city: '',
    tpmDeptId: null,
  },
  rules: {
    lineName: [{ required: true, message: '请输入', trigger: 'change' }],
    customerId: [{ required: true, message: '请输入', trigger: 'change' }],
    manMachineWiringRatio: [{ required: true, message: '请输入', trigger: 'change' }],
    humanMachineLineDefenseRatio: [{ required: true, message: '请选择', trigger: 'change' }],
    humanRobotClimbingRatio: [{ required: true, message: '请选择', trigger: 'change' }],
    chargeUser: [{ required: true, message: '请选择', trigger: 'change' }],
    levelOneRate: [{ required: true, message: '请选择', trigger: 'change' }],
    levelTwoRate: [{ required: true, message: '请选择', trigger: 'change' }],
    levelThreeRate: [{ required: true, message: '请选择', trigger: 'change' }],
    moduleCount: [{ required: true, message: '请选择', trigger: 'change' }],
    lineCount: [{ required: true, message: '请选择', trigger: 'change' }],
    customerProductName: [{ required: true, message: '请选择', trigger: 'change' }],
    tpmId: [{ required: true, message: '请选择', trigger: 'change' }],
    region: [{ required: true, message: '请选择', trigger: 'change' }],
    projectConfigId: [{ required: true, message: '请选择', trigger: 'change' }],
    stationConfigId: [{ required: true, message: '请选择', trigger: 'change' }],
    deptName: [{ required: true, message: '请选择', trigger: 'change' }],
  },
  detailInfo: null,
  title: null,
  selectList: [],
  selectedItem: null,
  areaOptions: [],
  projectCode: null,
  stationCode: null,
  deptList: [],
});

const {
  loading,
  open,
  formData,
  rules,
  detailInfo,
  title,
  selectList,
  selectedItem,
  areaOptions,
  projectCode,
  stationCode,
  deptList,
} = toRefs(compData);

onMounted(() => {
  if (route.params.id) {
    title.value = '编辑现场计划单';
  } else {
    title.value = '创建现场计划单';
  }
  selectData();
  getDeptData();
  getCrmCustomerArea(formData.value.customerId);
});

const getCrmCustomerArea = async id => {
  const params = {
    customerId: id,
  };
  const res = await Api.crm.crmCustomerArea.list(params);
  const { code, data } = res.data;
  if (code == 200) {
    areaOptions.value = data.records;
  }
};

// 获取数据
const getDeptData = async () => {
  try {
    loading.value = true;
    const params = { current: 1, size: 100 };
    const res = await Api.pdp.productDepartment.list(params);
    const { code, data } = res.data;
    if (code === 200) {
      deptList.value = data.records;
    }
  } catch (err) {
    console.error(err);
  } finally {
    loading.value = false;
  }
};
// 保存提交
const submitForm = async () => {
  proxy.$refs['ruleFormRef'].validate(async valid => {
    if (valid) {
      loading.value = true;
      // 检查三个输入框的总和是否超过 1
      const sum =
        Number(formData.value.levelOneRate) +
        Number(formData.value.levelTwoRate) +
        Number(formData.value.levelThreeRate);
      if (sum !== 100) {
        proxy.$message({
          type: 'error',
          message: 'L1、L2、L3人占比总和要等于百分之百，请调整后重新提交！',
        });
        return; // 阻止提交
      }
      const idString = proxy.arrayToIdsString({
        array: formData.value.attachment,
      });
      const form = {
        ...formData.value,
        attachment: idString,
        stationConfigId: formData.value.stationConfigId?.id
          ? formData.value.stationConfigId.id
          : formData.value.stationConfigId,
        projectConfigId: formData.value.projectConfigId?.id
          ? formData.value.projectConfigId.id
          : formData.value.projectConfigId,
        customerId: formData.value.customerId?.id
          ? formData.value.customerId.id
          : formData.value.customerId,
        levelTwoRate: formData.value.levelTwoRate / 100,
        levelThreeRate: formData.value.levelThreeRate / 100,
        levelOneRate: formData.value.levelOneRate / 100,
      };
      const res = await Api.pdp.mmrPlanOrder.submit(form);
      const { code } = res.data;
      if (code === 200) {
        loading.value = false;
        proxy.$message({ type: 'success', message: '保存成功' });
        closeDrawer();
      }
    }
  });
};

// 下拉数据
const selectData = async () => {
  const params = {
    current: 1,
    size: 100,
  };
  const res = await Api.pdp.mmrPlanOrder.select(params);
  const { code, data } = res.data;
  if (code == 200) {
    selectList.value = data.records;
  }
};

const changeCustomer = customer => {
  formData.value.cmCode = customer?.cmCode;
  formData.value.customerName = customer?.fullname;
};

const hanleProjectConfig = row => {
  projectCode.value = row;
  formData.value.projectCode = row?.projectCode;
};
const hanleStationConfig = row => {
  stationCode.value = row;
  formData.value.stationCode = row?.stationCode;
};

// 处理选择变化
const handleSelect = selectedValue => {
  selectedItem.value = selectList.value.find(item => item.fnumber === selectedValue);
};
// 取消
const closeDrawer = () => {
  emit('confirm');
  formData.value = {
    tpmId: null,
    customerProductCode: null,
    moduleCount: 1,
    lineCount: 1,
    levelOneRate: 30,
    levelTwoRate: 60,
    levelThreeRate: 10,
  };
  open.value = false;
  areaOptions.value = [];
};

// 打开抽屉
const openDrawer = async () => {
  open.value = true;
  await getRegion();
  if (route.params.id) {
    const params = {
      id: route.params.id,
    };

    const res = await Api.pdp.mmrPlanOrder.detail(params);
    const { code, data } = res.data;
    if (code == 200) {
      detailInfo.value = data;
      formData.value = detailInfo.value;
      formData.value.levelOneRate = data.levelOneRate * 100;
      formData.value.levelTwoRate = data.levelTwoRate * 100;
      formData.value.levelThreeRate = data.levelThreeRate * 100;
    }
  }
};

const getRegion = async () => {
  try {
    const res = await Api.system.region.getLazyTreeLevelThree();
    const { code, data } = res.data;
    if (code == 200) {
      areaOptions.value = data;
    }
  } catch (error) {
    console.error('获取区域数据失败', error);
    proxy.$message({ type: 'error', message: '获取区域数据失败' });
  }
};

// 级联选择器
const handleChange = value => {
  formData.value.region = [];
  formData.value.country = value ? value[0] : '';
  formData.value.province = value ? value[1] : '';
  formData.value.city = value && value.length > 2 ? value[2] : ''; // 如果 city 有值，则赋值，否则为空字符串
  formData.value.region = value ? value : null;
};

const handleTpmChange = row => {
  formData.value.tpmId = row.id;
  formData.value.tpmDeptId = row.deptId;
};

defineExpose({
  openDrawer,
});
</script>
<style lang="scss">
.wrap {
  .custom-form {
    display: flex;
    flex-wrap: wrap;

    .form-item-info {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
    }

    .form-itme-width {
      &_50 {
        width: 50%;
        margin-right: 0;
      }
      &_25 {
        width: 33%;
        margin-right: 0;
      }

      &_100 {
        width: 100%;
        margin-right: 0;
      }
    }

    .tag-group {
      padding: 0 12px;
      width: 100%;
      overflow: auto;

      .placeholder {
        color: var(--el-text-color-placeholder);
      }
    }
  }
}

@media (max-width: 1360px) {
  .form-itme-width_50 {
    width: 100% !important;
    margin-right: 0;
  }
}
</style>
<style lang="scss" scoped>
@use '@/styles/projectDrawer';

.plan-type {
  margin-right: 5px;
  padding: 2px 7px;
  border-radius: 3px;
  font-weight: 400;
  font-size: 12px;
  color: #fff;
  line-height: 10px;
}
</style>
<style lang="scss" scoped>
.wrap {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;

  .wrap-left-form {
    width: 95%;
  }

  .custom-form {
    margin: auto;
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }

  .form-center {
    display: flex;
    flex-wrap: wrap;
  }

  .form-group-title {
    display: flex;
    align-items: center;
    width: 100%;
    margin: 28px 0 32px 0;
    font-weight: 600;
    font-size: 16px;
    color: #333;

    &::before {
      margin-right: 4px;
      display: block;
      content: '';
      width: 4px;
      height: 13px;
      background-color: #f78431;
    }

    .add-box {
      display: flex;
      align-items: center;
      margin-left: 40px;
      font-weight: 400;
      font-size: 14px;
      color: #f78431;
      cursor: pointer;
    }
  }

  .form-item-row {
    width: 93% !important;
  }

  .form-item-width {
    width: 100%;
  }
}
.audit {
  :deep(.el-dialog__body) {
    height: auto !important;
  }
}
</style>
